one of the projects in my book asks me to write a recursive function that raises x to the power n. im given the formula that if the power is even x^n = (x^(n/2))^2 or if its odd x^n = x * x^(n-1)
here is the code
Code:
#include <stdio.h>
#include <stdlib.h>
int power(int x, int n);
int main()
{
int x, n, answer;
printf("Enter the value of x: ");
scanf(" %d", &x);
printf("Enter the value of n: ");
scanf(" %d", &n);
answer = power(x, n);
printf("%d to the power %d is %d\n", x, n, answer);
return 0;
}
int power(int x, int n)
{
if (n == 0)
{
return 1;
}
else if (n % 2 == 0) //check to see if the power is even or odd
{
return x * x * power(x, n / 2);
}
else
{
return x * power(x, n - 1);
}
}
if i enter 2 for x and 10 for n i get the answer 256 which is WRONG it should be 1024 if i enter 2 for x and 5 for n i get the answer 64 which again is WRONG it should be 32.
Obviously the function is wrong somewhere but i cant for the life of me see where.
many thanks
coop